//
//  ViewController.m
//  QZLabelViewController
//
//  Created by 吴清正 on 2017/4/13.
//  Copyright © 2017年 dazheng_wu. All rights reserved.
//

#import "QZLabelViewController.h"
#import <objc/runtime.h>
#import "Masonry.h"

@implementation QZLabelItem

@end

@interface QZLabelViewController () <UIPageViewControllerDataSource, UIPageViewControllerDelegate>
@property (nonatomic, assign)CGFloat buttonWidth;
@end

@implementation QZLabelViewController

static void * IndexKey = (void *)@"IndexKey";

+ (instancetype)instanceWithControllerArray:(NSArray *)__controllerArr titleArray:(NSArray *)__titleArr{
    QZLabelViewController *__vc = [[self alloc] init];
    __vc.titleArr = __titleArr;
    __vc.controllersArr = __controllerArr;

    return __vc;
}

- (void)viewDidLoad{
    [super viewDidLoad];

    if (self.titleArr.count == 0 || self.controllersArr.count == 0) return;

    [self reloadView];
}

- (void)reloadView{
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.tagScrollView];
    [self.view addSubview:self.pageViewController.view];
    [self configButton];

    [self.tagScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top).mas_offset(@0);
        make.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo(self.labelItem.buttonHeight);
    }];

    [self.pageViewController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.tagScrollView.mas_bottom).mas_offset(@0);
        make.bottom.mas_equalTo(self.view);
        make.left.right.mas_equalTo(self.view);
    }];

}

- (void)configButton{
    CGFloat space = 0.0;
    CGRect preBtnFrame = CGRectZero;
    int i = 0;

    for (NSString *title in self.titleArr) {
        CGSize nameSize = [title boundingRectWithSize:CGSizeMake(self.view.frame.size.width, 0) options:3 attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15]} context:nil].size;
        CGFloat bX = space + CGRectGetMaxX(preBtnFrame);
        CGFloat bY = 0;
        CGFloat bW = self.titleArr.count < 4 ? ([UIScreen mainScreen].bounds.size.width) / self.titleArr.count : nameSize.width + 20;
        CGFloat bH = self.labelItem.buttonHeight;
        _buttonWidth = bW;

        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(bX, bY, bW, bH);
        [btn setTitle:title forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitleColor:self.labelItem.titleNormalColor forState:UIControlStateNormal];
        [btn setTitleColor:self.labelItem.titleSelectColor forState:UIControlStateSelected];
        [btn setBackgroundImage:[UIImage imageNamed:@"btn_select"] forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];

        if ([title isEqualToString:self.titleArr[_currentPage]]) {
            btn.selected = YES;
        }

        btn.tag = 100 + i;
        [self.tagScrollView addSubview:btn];

        preBtnFrame  = btn.frame;
        i++;
    }

    self.tagScrollView.contentSize = CGSizeMake( CGRectGetMaxX(preBtnFrame) + 0.0, self.tagScrollView.bounds.size.height);
}

- (UIViewController *)returnTheCurrentDisplayVC{
    return [_controllersArr objectAtIndex:_currentPage];
}

#pragma mark - GET/SET

- (UIScrollView *)tagScrollView{
    if (!_tagScrollView) {
        _tagScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ([UIScreen mainScreen].bounds.size.width), self.labelItem.buttonHeight)];
        _tagScrollView.backgroundColor = [UIColor cyanColor];
        _tagScrollView.showsVerticalScrollIndicator = NO;
        _tagScrollView.showsHorizontalScrollIndicator = NO;
        _tagScrollView.bounces = NO;
    }

    return _tagScrollView;
}

- (UIPageViewController *)pageViewController{
    if (!_pageViewController) {
        _pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
                                                              navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                                                                            options:nil];
        [_pageViewController setViewControllers:@[_controllersArr[self.currentPage]]
                                      direction:UIPageViewControllerNavigationDirectionForward
                                       animated:NO
                                     completion:nil];
        _pageViewController.view.backgroundColor = [UIColor whiteColor]/*[UIColor wyp_colorWithHex:0xEBEBF1]*/;
        _pageViewController.delegate = self;
        _pageViewController.dataSource = self;
        _pageViewController.doubleSided = YES;
    }

    return _pageViewController;
}

- (void)setControllersArr:(NSArray *)controllersArr{
    [controllersArr enumerateObjectsUsingBlock:^(UIViewController *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        objc_setAssociatedObject(obj, IndexKey, [NSNumber numberWithInteger:idx], OBJC_ASSOCIATION_COPY_NONATOMIC);
    }];

    _controllersArr = controllersArr;
}

#pragma mark - 设置按钮选择 PageViewController

- (void)setViewController:(NSInteger)index{
    [_pageViewController setViewControllers:@[_controllersArr[index]]
                                  direction:index < _currentPage
                                   animated:YES
                                 completion:nil];
    _currentPage = index;
}

- (void)clickAction:(UIButton *)btn{
    for (int i = 0; i < _tagScrollView.subviews.count; i++) {
        UIView *view = _tagScrollView.subviews[i];
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *)view;
            btn.selected = NO;
            btn.backgroundColor = [UIColor clearColor];
        }
    }
    btn.selected = YES;
    NSInteger index = btn.tag - 100;

    [self setViewController:index];
}

- (void)refreshButton{
    for (int i = 0; i < _tagScrollView.subviews.count; i++) {
        UIView *view = _tagScrollView.subviews[i];
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *)view;
            btn.selected = NO;
            btn.backgroundColor = [UIColor clearColor];
            if (btn.tag == 100 + _currentPage) {
                btn.selected = YES;
            }
        }
    }
}

#pragma mark - <UIPageViewControllerDataSource,UIPageViewControllerDelegate>

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController{
    NSInteger index =  [objc_getAssociatedObject(viewController, IndexKey) integerValue];
    index--;
    if (index < 0) return nil;

    return _controllersArr[index];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController{
    NSInteger index =  [objc_getAssociatedObject(viewController, IndexKey) integerValue];
    index++;
    if (index >= _controllersArr.count) return nil;

    return _controllersArr[index];
}

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed{
    if (finished) {
        NSInteger index =  [objc_getAssociatedObject(pageViewController.viewControllers[0], IndexKey) integerValue];
        _currentPage = index;
        [self refreshButton];

        if ((index +1) * _buttonWidth > _tagScrollView.frame.size.width) {
            NSInteger index_button =  ((index + 1) * _buttonWidth - _tagScrollView.frame.size.width) / _buttonWidth + 1;
            _tagScrollView.contentOffset = CGPointMake(_buttonWidth * index_button, 0);
        }
        else if ((_titleArr.count  - index) * _buttonWidth >= _tagScrollView.frame.size.width){
            _tagScrollView.contentOffset = CGPointMake(0, 0);
        }
        
    }
}

@end
